package com.huaxin.hxcloud.activity;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.StationTaskDetail;
import com.huaxin.common.Entity.WorkFlowTaskDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.SpacesItemDecoration;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.Adapter.HorizontalStationAdapter;
import com.huaxin.hxcloud.Adapter.TaskXunJianPlanAdapter;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author lwjing
 * @date 2018/3/21
 * @Desc $desc$
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxXunJianCheckActivity extends BaseActivity implements BaiduMap.OnMapLoadedCallback, SensorEventListener, View.OnClickListener {

    @BindView(R.id.more)
    TextView more;
    @BindView(R.id.toolbar)
    Toolbar  mToolbar;
    @BindView(R.id.tv_task_code)
    TextView tv_task_code;
    @BindView(R.id.tv_time_task_done)
    TextView tv_time_task_done;
    @BindView(R.id.tv_task_name)
    TextView tv_task_name;
    @BindView(R.id.tv_task_begin_time)
    TextView tv_task_begin_time;
    @BindView(R.id.tv_task_duration)
    TextView tv_task_duration;
    @BindView(R.id.tv_task_worker)
    TextView tv_task_worker;

    @BindView(R.id.tv_in_time)
    TextView mTvInTime;
    @BindView(R.id.tv_done)
    TextView mTvDone;
    @BindView(R.id.tv_mix_check)
    TextView mTvMixCheck;
    @BindView(R.id.tv_exption)
    TextView mTvExption;

    @BindView(R.id.mapview_station)
    TextureMapView mMapviewStation;
    @BindView(R.id.rl_station_xunjian)
    RecyclerView   rl_horizontal_Station;
    @BindView(R.id.rl_task_xunjian)
    RecyclerView   rl_task;
    @BindView(R.id.ll_percent)
    LinearLayout   ll_percent;

    List<StationTaskDetail>          stationArr = new ArrayList<>();
    List<StationTaskDetail.TaskItem> taskItems  = new ArrayList<>();
    private TaskXunJianPlanAdapter               taskAdapter;
    private HorizontalStationAdapter             horizongtalStationAdapter;
    private BaiduMap                             mBaiduMap;
    private LocationClient                       mLocClient;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationConfiguration              mConfiguration;
    private SensorManager                        mSensorManager;
    private BitmapDescriptor                     mCurrentMarker;

    /**
     * 定位SDK监听函数
     */
    private int    mCurrentDirection = 0;
    private double mCurrentLat       = 0.0;
    private double mCurrentLon       = 0.0;
    private float          mCurrentAccracy;
    private MyLocationData locData;
    boolean isFirstLoc = true; // 是否首次定位
    private Double        lastX     = 0.0;
    private List<Overlay> mOverlays = new ArrayList<>();
    private String arrangeId;
    //当前选择的站点
    private int currentPos = 0;
    private HxSationDialogFragment mDialogFrament;
    private String                 taskId;
    //考核归档 和 巡检计划确认
    private int                    taskType;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_xunjian_check;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_ARRANGE_ID)) {
            arrangeId = extras.getString(Constants.IK_ARRANGE_ID);
            taskId = extras.getString(Constants.IK_TASK_ID);
            taskType = extras.getInt(Constants.IK_TASK_TYPE); //4 表示归档考核
        } else {
            finish();
        }
    }

    @Override
    public void initView() {
        setSupportActionBar(mToolbar);
        if (taskType == 4) {
            mToolbar.setTitle("巡检单归档");
            more.setText("确认");
        } else {
            mToolbar.setTitle("巡检单审核");
            more.setText("审核");
        }

        more.setOnClickListener(this);
        initMap();
        LinearLayoutManager horizontalMa = new LinearLayoutManager(this);
        horizontalMa.setOrientation(LinearLayoutManager.HORIZONTAL);
        rl_horizontal_Station.setLayoutManager(horizontalMa);
        horizongtalStationAdapter = new HorizontalStationAdapter(R.layout.item_string, stationArr);
        rl_horizontal_Station.setAdapter(horizongtalStationAdapter);
        rl_task.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        taskAdapter = new TaskXunJianPlanAdapter(R.layout.item_xunjian_plan, taskItems);
        rl_task.setAdapter(taskAdapter);
        rl_task.addItemDecoration(new SpacesItemDecoration(30));

        horizongtalStationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                if (currentPos == position) {
                    return;
                }
                //站点切换
                StationTaskDetail stationTaskDetail = stationArr.get(position);
                stationTaskDetail.setCheck(true);
                stationArr.get(currentPos).setCheck(false);
                horizongtalStationAdapter.notifyDataSetChanged();
                taskItems.clear();
                taskAdapter.setNewData(taskItems);
                //TODO 根据站点刷新任务列表
                taskItems.addAll(stationArr.get(position).getItemArr());
                taskItems.addAll(stationArr.get(position).getWaterArr());
                taskAdapter.setNewData(taskItems);
                currentPos = position;

            }
        });

    }

    /**
     * 更新UI
     *
     * @param workFlowTaskDTO
     */
    private void updataView(WorkFlowTaskDTO workFlowTaskDTO) {
        WorkFlowTaskDTO.WorkFlowTaskDetail workFlowTaskDetail = workFlowTaskDTO.getData();
        if (workFlowTaskDetail == null) {
            updateLoadStatus(LOAD_NO_DATA);
            return;
        }
        //更新界面
        loadTextColon(tv_task_code, "工单编号", workFlowTaskDetail.getCode());
        if (workFlowTaskDetail.getRequire() != 0) {
            loadTextColon(tv_time_task_done, "要求完成时间", dateFormat(workFlowTaskDetail.getRequire()));
        }
        if (workFlowTaskDetail.getStart() != 0) {
            loadTextColon(tv_task_begin_time, "开始时间", dateFormat(workFlowTaskDetail.getStart()));
        } else if (workFlowTaskDetail.getEndTime() != 0) {
            loadTextColon(tv_task_begin_time, "结束时间", dateFormat(workFlowTaskDetail.getEndTime()));
        }

        loadTextColon(tv_task_name, "工单名称", workFlowTaskDetail.getTitle());
        loadTextColon(tv_task_worker, "负责人", workFlowTaskDetail.getPrincipal());
        loadTextColon(tv_task_duration, "巡检周期", "");
        ll_percent.setVisibility(View.GONE);
        //默认选中第一个站点
        stationArr.addAll(workFlowTaskDetail.getStationArr());
        if (stationArr.size() > 0) {
            stationArr.get(0).setCheck(true);
        }
        horizongtalStationAdapter.setNewData(stationArr);
        //巡检站点
        initMark();
        //巡检项目 默认第一个
        if (stationArr.size() > 0) {
            taskItems.addAll(stationArr.get(0).getItemArr());
            taskItems.addAll(stationArr.get(0).getWaterArr());
            taskAdapter.setNewData(taskItems);
        }
    }

    @Override
    protected void requestData() {
        super.requestData();
        apiXunJianDetail();
    }

    private void apiXunJianDetail() {
        updateLoadStatus(LOADING);
        Call<WorkFlowTaskDTO> call = HxTransmitRequestHelper.getRequestApi().getXunJianDetail(arrangeId);
        autoClose(call);
        android.util.Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<WorkFlowTaskDTO>() {
            @Override
            public void onResponse(Call<WorkFlowTaskDTO> call, Response<WorkFlowTaskDTO> response) {
                WorkFlowTaskDTO workFlowTaskDTO = response.body();
                if (response.isSuccessful() && workFlowTaskDTO != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    //更新界面
                    updataView(workFlowTaskDTO);
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<WorkFlowTaskDTO> call, Throwable t) {
                android.util.Log.d(TAG, "onFailure: ---->" + t);
                updateLoadStatus(LOAD_FAILURE);

            }
        });
    }


    /**
     * 初始化地图
     */
    private void initMap() {
        mBaiduMap = mMapviewStation.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setBuildingsEnabled(false);
        initLocation();
        //    initMark();
        mBaiduMap.setOnMapLoadedCallback(this);
        //解决地图滑动和scollview滑动的冲突
        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent ev) {
                switch (ev.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        mMapviewStation
                                .requestDisallowInterceptTouchEvent(true);
                        break;
                    default:
                        mMapviewStation
                                .requestDisallowInterceptTouchEvent(false);
                        break;
                }
            }
        });
    }

    private void initMark() {
        List<OverlayOptions> optionList = new ArrayList<>();
        List<LatLng> points = new ArrayList<LatLng>();
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (StationTaskDetail stationTaskDetail : stationArr) {
            if (!(stationTaskDetail.getLat() == 0.0) || !(stationTaskDetail.getLng() == 0.0)) {
                android.util.Log.d(TAG, "initMark: ---->" + stationTaskDetail.toString());
                // Bundle bundle = new Bundle();
                // bundle.putParcelable(Constants.IK_STATION, station);
                LatLng point = new LatLng(stationTaskDetail.getLat(), stationTaskDetail.getLng());
                points.add(point);
                builder = builder.include(point);
                MarkerOptions option = new MarkerOptions()
                        .position(point)
                        .icon(getBDescriptor(stationTaskDetail.getState()));
                //  .extraInfo(bundle);
                //                    .animateType(MarkerOptions.MarkerAnimateType.drop);
                optionList.add(option);
            }

        }
        mOverlays = mBaiduMap.addOverlays(optionList);

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                // updateStationInfo(marker);
                return true;
            }
        });
    }

    private BitmapDescriptor getBDescriptor(int state) {
        BitmapDescriptor bitmapDescriptor;
        //  1.未开始 2.处理中 3.已完成
        switch (state) {
            case 1:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_no_check);
                break;
            case 2:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_exception_check);
                break;
            case 3:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_normal_check);
                break;
            default:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_normal_check);
                break;
        }
        return bitmapDescriptor;
    }

    /**
     * @desc 初始定位
     * @author songxf
     * created at 2017/7/12 16:03
     */
    private void initLocation() {
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(new MyLocationListenner());
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mConfiguration = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfigeration(mConfiguration);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于
        mLocClient.setLocOption(option);
        mLocClient.start();
        //  mBaiduMap.
    }

    @Override
    public void onMapLoaded() {
        final LatLngBounds.Builder builder = new LatLngBounds.Builder();
        if (!(mOverlays.size() == 0)) {
            for (Overlay overlay : mOverlays) {
                builder.include(((Marker) overlay).getPosition());
            }
            //设置多个覆盖物，地图的缩放比例
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(builder.build().getCenter(), 6.5f));
        }
    }

    @Override
    protected void onResume() {
        mMapviewStation.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
        super.onResume();

    }

    @Override
    protected void onPause() {
        mMapviewStation.onPause();
        super.onPause();

    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapviewStation.onDestroy();
        mMapviewStation = null;
        super.onDestroy();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more:
                //巡检单审核
                mDialogFrament = HxSationDialogFragment.newInstance();
                mDialogFrament.show(getFragmentManager(), "image");
                Bundle bundle = new Bundle();
                bundle.putBoolean(Constants.DIALOG_IS_PHONE, false);
                if (taskType == 4) {
                    bundle.putString(Constants.DIALOG_CANCLE_STR, "取消");
                    bundle.putString(Constants.DIALOG_UPLOADBTN_STR, "确认归档");
                } else {
                    bundle.putString(Constants.DIALOG_CANCLE_STR, "不通过");
                    bundle.putString(Constants.DIALOG_UPLOADBTN_STR, "通过");
                }
                mDialogFrament.setArguments(bundle);
                mDialogFrament.setCancelable(true);
                mDialogFrament.setLoadLisetener(new HxSationDialogFragment.UpLoadLisetener() {
                    @Override
                    public void upload() {
                        mDialogFrament.dismiss();

                        //同意  0通过 1不通过
                        if (taskType == 4) {
                            apiExamineTask(mDialogFrament.getDes(), 0);
                        } else {
                            apiTaskCheck(mDialogFrament.getDes(), 0);
                        }
                    }
                });
                mDialogFrament.setCancleLisetener(new HxSationDialogFragment.CancleLisetener() {
                    @Override
                    public void cancle() {
                        mDialogFrament.dismiss();
                        if (taskType == 4) {
                            return;
                        }
                        if (!TextUtils.isEmpty(mDialogFrament.getDes())) {
                            apiTaskCheck(mDialogFrament.getDes(), 1);
                        } else {
                            ToastUtil.showToast("请填写不通过的原因");
                        }
                    }
                });
                break;
        }
    }

    /**
     * 考核归档
     *
     * @param des
     * @param checkType
     */
    private void apiExamineTask(String des, int checkType) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().getExamineTask(taskId, des);
        autoClose(call);
        android.util.Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO dto = response.body();
                if (response.isSuccessful()) {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    finish();
                } else {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    ToastUtil.showToast("数据异常，请重新审核");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                android.util.Log.d(TAG, "onFailure: ---->" + t);
                ToastUtil.showToast("网络请求失败，请重新审核");
            }
        });
    }

    /**
     * 审核提交
     *
     * @param des
     * @param checkType
     */
    private void apiTaskCheck(String des, int checkType) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().getTaskCheck(taskId, checkType, des);
        autoClose(call);
        android.util.Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO dto = response.body();
                if (response.isSuccessful()) {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    finish();
                } else {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    ToastUtil.showToast("数据异常，请重新审核");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                android.util.Log.d(TAG, "onFailure: ---->" + t);
                ToastUtil.showToast("网络请求失败，请重新审核");
            }
        });
    }

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mBaiduMap == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(6.5f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }
    }
}
